<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('team.editTeam')"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="top"
    >
      <el-form-item :label="$t('team.teamName')" prop="name">
        <el-input
          v-model="form.name"
          :placeholder="$t('team.teamNamePlaceholder')"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item :label="$t('team.teamDescription')" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :placeholder="$t('team.teamDescriptionPlaceholder')"
          :rows="4"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('team.maxMembers')" prop="maxMembers">
            <el-input-number
              v-model="form.maxMembers"
              :min="currentMemberCount"
              :max="200"
              :step="1"
              style="width: 100%"
            />
            <div class="form-tip">
              {{ $t('team.maxMembersTip', { current: currentMemberCount }) }}
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('team.teamAvatar')" prop="teamAvatarUrl">
            <el-input
              v-model="form.teamAvatarUrl"
              :placeholder="$t('team.teamAvatarPlaceholder')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 头像预览 -->
      <el-form-item v-if="form.teamAvatarUrl">
        <div class="avatar-preview">
          <el-avatar :size="64" :src="form.teamAvatarUrl" />
          <span class="preview-label">{{ $t('team.avatarPreview') }}</span>
        </div>
      </el-form-item>

      <!-- 团队信息 -->
      <el-card class="team-info-card" shadow="never">
        <template #header>
          <span>{{ $t('team.teamInfo') }}</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item :label="$t('team.teamId')">
            {{ team?.id }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('team.status')">
            <el-tag :type="getTeamStatusType(team?.status)">
              {{ getTeamStatusLabel(team?.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('team.currentMembers')">
            {{ team?.currentMembers }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('team.created')">
            {{ formatDate(team?.createdAt) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
        >
          {{ $t('common.save') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormInstance, FormRules } from 'element-plus'
import { useTeamStore } from '@/stores/teamStore'
import type { Team, UpdateTeamRequest } from '@/types/team'
import { getTeamStatusLabel, getTeamStatusType } from '@/types/team'
import { formatDate } from '@/utils/date'

interface Props {
  modelValue: boolean
  team: Team | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()

const teamStore = useTeamStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = reactive<UpdateTeamRequest>({
  name: '',
  description: '',
  maxMembers: 50,
  teamAvatarUrl: ''
})

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 当前成员数量
const currentMemberCount = computed(() => {
  return props.team?.currentMembers || 0
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: t('team.teamNameRequired'), trigger: 'blur' },
    { min: 2, max: 50, message: t('team.teamNameLength'), trigger: 'blur' }
  ],
  description: [
    { max: 500, message: t('team.teamDescriptionLength'), trigger: 'blur' }
  ],
  maxMembers: [
    { required: true, message: t('team.maxMembersRequired'), trigger: 'blur' },
    { 
      type: 'number', 
      min: currentMemberCount.value, 
      max: 200, 
      message: t('team.maxMembersEditRange', { min: currentMemberCount.value }), 
      trigger: 'blur' 
    }
  ],
  teamAvatarUrl: [
    { type: 'url', message: t('team.teamAvatarInvalid'), trigger: 'blur' }
  ]
}

// 方法
const handleSubmit = async () => {
  if (!formRef.value || !props.team) return

  try {
    await formRef.value.validate()
    
    loading.value = true
    await teamStore.updateTeam(props.team.id, form)
    
    emit('success')
  } catch (error) {
    console.error('更新团队失败:', error)
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const initForm = () => {
  if (props.team) {
    Object.assign(form, {
      name: props.team.name,
      description: props.team.description || '',
      maxMembers: props.team.maxMembers,
      teamAvatarUrl: props.team.teamAvatarUrl || ''
    })
  }
}

// 监听对话框打开和团队数据变化
watch([dialogVisible, () => props.team], ([visible, team]) => {
  if (visible && team) {
    initForm()
  }
}, { immediate: true })
</script>

<style scoped lang="scss">
.avatar-preview {
  display: flex;
  align-items: center;
  gap: 12px;

  .preview-label {
    font-size: 14px;
    color: var(--el-text-color-regular);
  }
}

.team-info-card {
  margin-top: 20px;
  
  :deep(.el-card__header) {
    padding: 12px 20px;
    background: var(--el-bg-color-page);
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
}

.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }

  .el-row {
    .el-col {
      margin-bottom: 20px;
    }
  }
}
</style>
